package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.api.ISysOrg;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.extend.service.ExtendSysOrgService;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdTeamPeople;
import com.ccp.dev.qbdms.service.WQbdFalSuperviseService;
import com.ccp.dev.qbdms.service.WQbdTeamPeopleService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.SysOrg;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 质量人员 信息操作处理控制器
 * 
 * @author zhl
 * @date 2020-07-06 09:00:29
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "质量体系审核员")
@RequestMapping("/qbdms/wQbdTeamPeople")
public class WQbdTeamPeopleController extends SysBaseController{
	@Resource
	private WQbdTeamPeopleService wQbdTeamPeopleService;
    @Resource
    private ExtendSysOrgService extendSysOrgService;
    @Resource
    private WQbdFalSuperviseService wQbdFalSuperviseService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: zhl
     * @date: 2020-07-06 09:00:29
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到质量人员首页", exectype = "页面跳转日志")
    public String viewList(ModelMap modelMap) {
        // 当前系统等级
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        modelMap.put("currentSystemLevel", currentSystemLevel);
        modelMap.put("userId", ContextUtil.getCurrentUserId());
// 只能看到下级单位,以及当前单位
        ISysOrg currentOrg = ContextUtil.getCurrentOrg();
        HashMap<String, String> hashMap = new HashMap<>(16);
        List<Map> org;
        if (BaseUtil.SystemLevel.GROUPLEVEL.equals(currentSystemLevel)) {
            // 集团看所有
            // 需要参数的时候直接放入hashMap
            hashMap.put("current", "0");
            org = wQbdFalSuperviseService.getOrg2(hashMap);
        } else {
            // 二级，三级单位看本单位以及全部三级单位
            hashMap.put("ORGSUPID", currentOrg.getOrgId());
            hashMap.put("ISTENANT", "1");
            hashMap.put("this", "this");
            org = wQbdFalSuperviseService.getOrg(hashMap);
//            org.removeIf(sysOrg -> "1".equals(sysOrg.get("ISTENANT")));
        }

        modelMap.put("org", JSON.toJSONString(org));
        return "wQbdTeamPeople/list";
    }

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: zhl
    * @date: 2020-07-06 09:00:29
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询质量人员",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        // 默认按照创建时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "createtime");
            queryFilter.addFilter("orderSeq", "desc");
        }
        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<WQbdTeamPeople> pageDatas = wQbdTeamPeopleService.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        // 添加编辑按钮权限控制
        ZhiLiangConst.isDataAllowEdit(pageDatas, false);

        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: zhl
     * @date: 2020-07-06 09:00:29
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到质量人员新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        if(StringUtil.isEmpty(id)){
            SysOrg tenOrg =  extendSysOrgService.getTenOrg(ContextUtil.getCurrentUserId());
            modelMap.put("code",tenOrg.getCode());
            modelMap.put("orgName",tenOrg.getOrgName());
        }
        return "wQbdTeamPeople/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wQbdTeamPeople 保存的对象
    * @return: java.lang.Object
    * @auther: zhl
    * @date: 2020-07-06 09:00:29
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存质量人员数据",detail="<#if isAdd>新增<#else>编辑</#if>质量人员数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdTeamPeople wQbdTeamPeople) {
        String id = wQbdTeamPeople.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            //新增数据前生成随机Id
            wQbdTeamPeople.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdTeamPeople);
            //上报状态
            BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();

            if (BaseUtil.SystemLevel.GROUPLEVEL.equals(currentSystemLevel)) {
                wQbdTeamPeople.setReportStatus(ZhiLiangConst.GROUP_ADD);
            } else if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(currentSystemLevel)) {
                wQbdTeamPeople.setReportStatus(ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED);
            } else if (BaseUtil.SystemLevel.PLANTLEVEL.equals(currentSystemLevel)) {
                wQbdTeamPeople.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            }

            result = wQbdTeamPeopleService.add(wQbdTeamPeople);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            ZhiLiangConst.updateCommonFields(wQbdTeamPeople);
            //修改操作
            result = wQbdTeamPeopleService.update(wQbdTeamPeople);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdTeamPeopleService.getOneById(id), wQbdTeamPeople));

        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: zhl
    * @date: 2020-07-06 09:00:29
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到质量人员详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        String isClose = RequestUtil.getString(request,"isClose");
        modelMap.put("id",id);
        modelMap.put("isClose",isClose);
        return "wQbdTeamPeople/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: zhl
    * @date: 2020-07-06 09:00:29
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询质量人员的一条数据",detail="根据主键id查询质量人员的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdTeamPeople wQbdTeamPeople = wQbdTeamPeopleService.getOneById(id);
        if (null == wQbdTeamPeople) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdTeamPeople);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: zhl
    * @date: 2020-07-06 09:00:29
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除质量人员数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdTeamPeople wQbdTeamPeople = wQbdTeamPeopleService.getOneById(key);
            if (!userId.equals(wQbdTeamPeople.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
            if (Objects.nonNull(wQbdTeamPeople.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(wQbdTeamPeople.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED.equals(wQbdTeamPeople.getReportStatus()) && !ZhiLiangConst.GROUP_ADD.equals(wQbdTeamPeople.getReportStatus())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待上报、待报集团的数据");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        int result = wQbdTeamPeopleService.delByIdArray(id.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }




    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到质量人员导出字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdTeamPeople.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }


    /**
    * 功能描述: 跳转到导入页面
    *
    * @return: java.lang.String
    * @auther: hw
    * @date: 2019-12-25 19:21:40
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到质量人员导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdTeamPeople/import";
    }

    /**
    * 功能描述: 导出质量人员数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: zhl
    * @date: 2020-07-06 09:00:29
    */
    @RequestMapping("/exportData")
    @Action(description="导出质量人员数据信息",detail="导出质量人员数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        // 默认按照创建时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "CREATETIME");
            queryFilter.addFilter("orderSeq", "desc");
        }
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter,id);
        List<WQbdTeamPeople> wQbdQcGroups = this.wQbdTeamPeopleService.queryAll(queryFilter);
        if (wQbdQcGroups.isEmpty()) {
            wQbdQcGroups.add(new WQbdTeamPeople());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, wQbdQcGroups, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
    * 导入资源文件
    * @param request
    * @param response
    * @throws Exception
    */
    @RequestMapping("/importData")
    @ResponseBody
    @Action(description = "导入质量体系审核员", detail = "导入质量体系审核员<#if success>成功<#else></#if>")
    public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
        Map<String, Object> map = new AbstractImpUtil() {
            @Override
            public ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;

                if ("idcode".contains(fieldName)) {
                    returnType = new ReturnType();
                    boolean matches = fieldValue.matches("(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$|^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)");
                    if (!matches) {
                        returnType.setMsg("身份证号格式不正确！");
                    } else {
                        returnType.setNewValue(fieldValue);
                    }
                }

                if ("contactinformation".contains(fieldName)) {
                    returnType = new ReturnType();
                    boolean matches = fieldValue.matches("(^1[3456789]\\d{9}$)");
                    if (!matches) {
                        returnType.setMsg("联系方式格式不正确，请输入正确的手机号码！");
                    } else {
                        returnType.setNewValue(fieldValue);
                    }
                }


                // 校验位置
                return returnType;
            }
        }.reverseModels(excelEntity, WQbdTeamPeople.class);
        String msg = map.get("msg").toString();
        List<WQbdTeamPeople> list = (List<WQbdTeamPeople>) map.get("instList");
        if (StringUtil.isEmpty(msg)) {
            this.wQbdTeamPeopleService.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("dataSource.importXml.success");
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail(msg);
        }
    }

    /**
     * 查询上报的信息
     *
     * @param request
     * @param id
     * @param tableName
     * @return
     */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(HttpServletRequest request, @RequestParam("id") String id, @RequestParam("tableName") String tableName) {
        //业务数据
        List<WQbdTeamPeople> reportList = wQbdTeamPeopleService.reportList(id, tableName);
        for (WQbdTeamPeople wQbdTeamPeople : reportList) {
            try {
                // 上报状态显示名称
                wQbdTeamPeople.setReportStatusStr(ZhiLiangConst.getStatusStrByInt(wQbdTeamPeople.getReportStatus()));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }


}
